package com.sunnada.edu.business.attendance.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.multipart.MultipartFile;

import com.sunnada.edu.business.attendance.dao.AttenRecordDao;
import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.common.EXCELObject;
import com.sunnada.edu.system.pub.common.MD5;
import com.sunnada.edu.system.pub.common.RandomTool;
import com.sunnada.edu.system.pub.dao.PubDao;
import com.sunnada.edu.system.pub.service.RandomGUID;
import com.sunnada.edu.system.pub.util.DateUtil;
import com.sunnada.edu.system.pub.util.Utils;

@Service
@Transactional
public class AttenRecordServiceImpl implements AttenRecordService {
	private static final Logger logger = LoggerFactory.getLogger(AttenRecordServiceImpl.class);
	@Resource
	AttenRecordDao attenRecordDao;

	@Override
	public int getAttenRecordCots(HashMap<String, String> params) {
		return attenRecordDao.getAttenRecordCots(params);
	}

	@Override
	public List<?> findAttenRecord(HashMap<String, String> params) {
		return attenRecordDao.findAttenRecord(params);
	}

	@Override
	public String attendanceDelete(HashMap<String, String> params) {
		String msg = "";
		int num = attenRecordDao.attendanceDelete(params);
		if (num == 0) {
			msg = "删除失败!";
		}
		return msg;
	}

	@Override
	public String attenRecordAdd(HashMap<String, String> params) {
		String msg = "";
			int num = attenRecordDao.attenRecordAdd(params);
			if (num == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
			}

		return msg;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String attenRecordDataUpdate(HashMap<String, String> params) {
		Map t =getAttenRecordData(params);
		String signTime1 = (String)t.get("SIGN_TIME1");
		String signoutTime = (String)t.get("SIGNOUT_TIME");
		String signTime2 = (String)t.get("SIGN_TIME2");
		String signoutTime2 = (String)t.get("SIGNOUT_TIME2");
		String signTime = (String) t.get("SIGN_TIME");
		String clockTime = params.get("signTime");
		 int debitType = Integer.parseInt((String) t.get("DEBIT_TYPE"));
		String lateTmie1 = (String) t.get("LATE_TMIE1");
		String lateTmie2 = (String) t.get("LATE_TMIE2");
		String lateTmie3 = (String) t.get("LATE_TMIE3");
		int timeBase = Integer.parseInt((String) t.get("TIMEBASE"));
		String num = (String) t.get("NUM");
		String attendanceStatu = "1";
		String lateTime = "";
		String amount = "";
		DateFormat df2 = new SimpleDateFormat("HH:mm:ss");
		  HashMap<String, String> p1 = new HashMap<String, String>();
		  p1.put("recId", params.get("recId"));
		  
		  //判断修改的是第几次打卡
		  if(num.equals("1") || num.equals("3") ){
			  p1.put("num", "2"); 
			  if(num.equals("3")){
				  p1.put("num", "4"); 
			  }
			 Map t1 =getAttenRecordData(p1);
			 String amount1 = "0";
			 String attendanceStatu1 = (String)t1.get("ATTENDANCE_STATU");
			 String lateTime1 = "0";
			 String clockTime1 = (String)t1.get("CLOCK_TIME");
			 String signoutTimes =(String)t1.get("SIGN_TIME");
			 if(Utils.isNotNull(clockTime)){
					try
					{
			  		    Date sg = df2.parse(signTime);
			  		    Date ct = df2.parse(clockTime);
			  		    	if((sg.getTime() - ct.getTime())>=0 ){
			   		    	   attendanceStatu = "1";
			 				}else{
			 					   long diff = ct.getTime() - sg.getTime();
			 					   if(Integer.parseInt(lateTmie1)>=(diff/60000)){
			 						   attendanceStatu = "1";
			 					   }else if(Integer.parseInt(lateTmie2)<(diff/60000) &&Integer.parseInt(lateTmie3)>(diff/60000)){
			 						  if(attendanceStatu1.equals("5")){
			 							 lateTime = "0";
				 						 amount = "0"; 
			 						  }else{
			 							 DecimalFormat    def   = new DecimalFormat("######0.00"); 
				 						 lateTime = def.format((diff/60000.0))+"";
				 						 amount = def.format((diff/60000.0/timeBase)*debitType)+"";  
				 						 lateTime = lateTime.substring(0, lateTime.indexOf("."));
										 amount = amount.substring(0, amount.indexOf("."));
			 						  }
			 						 attendanceStatu = "2";
			 					   }else{
			 						  lateTime = AttendanceMethods.TimeDifference(signTime1,signoutTime);
			 						   if(num.equals("3")){
			 							 lateTime = AttendanceMethods.TimeDifference(signTime2,signoutTime2);
			 						  }
									   
							    	   attendanceStatu = "5";
			 					   }
			 				}
					}
					catch (Exception e)
					{
					}
				}else{
					attendanceStatu = "4";
				}
			 
			 if(!attendanceStatu1.equals("1") && !attendanceStatu1.equals("4") ){
					try
					{
			  		    Date sg = df2.parse(signoutTimes);
			  		    Date ct = df2.parse(clockTime1);
			  		  if((ct.getTime() - sg.getTime())>=0 ){
			  			attendanceStatu1 = "1";
		 				}else{
		 					   long diff = sg.getTime() - ct.getTime();
		 					   if(Integer.parseInt(lateTmie1)>=(diff/60000)){
		 						  attendanceStatu1 = "1";
		 					   }else if(Integer.parseInt(lateTmie2)<(diff/60000) &&Integer.parseInt(lateTmie3)>(diff/60000)){
		 						  if(attendanceStatu.equals("5")){
		 							 lateTime1 = "0";
			 						   amount1 = "0";
		 						  }else{
		 							 DecimalFormat    def   = new DecimalFormat("######0.00");  
			 						   lateTime1 = def.format((diff/60000.0))+"";
			 						   amount1 = def.format((diff/60000.0/timeBase)*debitType)+"";
			 						   lateTime1 = lateTime1.substring(0, lateTime1.indexOf("."));
									   amount1 = amount1.substring(0, amount1.indexOf("."));
		 						  }
		 						 attendanceStatu1 = "3";
		 					   }else{
		 						  if(attendanceStatu.equals("5")){
		 							 lateTime1 ="0";
		 						  }else{
		 							 lateTime1 = AttendanceMethods.TimeDifference(signTime1,signoutTime);
		 							 if(num.equals("3")){
			 							 lateTime1 = AttendanceMethods.TimeDifference(signTime2,signoutTime2);
			 						  }
		 						  }
								   attendanceStatu1 = "5";
		 					   }
		 				}
					}
					catch (Exception e)
					{
					}
				}
			 p1.put("attendanceStatu", attendanceStatu1);
			 p1.put("amount", amount1);
			 p1.put("lateTime", lateTime1);
			 p1.put("clockTime", clockTime1);
			 int n = attenRecordDao.attenRecordDataUpdate(p1);
		  }else{
			 p1.put("num", "1"); 
			 if(num.equals("4")){
				  p1.put("num", "3"); 
			  }
		     Map t1 =getAttenRecordData(p1);
		     String amount1 = "0";
			 String attendanceStatu1 = (String)t1.get("ATTENDANCE_STATU");
			 String lateTime1 = "0";
			 String clockTime1 = (String)t1.get("CLOCK_TIME");
			 String signTimes =(String)t1.get("SIGN_TIME");
			 if(Utils.isNotNull(clockTime)){
					try
					{
			  		    Date sg = df2.parse(signTime);
			  		    Date ct = df2.parse(clockTime);
			  		    	if((ct.getTime() - sg.getTime())>=0 ){
			   		    	   attendanceStatu = "1";
			 				}else{
			 					   long diff = sg.getTime() - ct.getTime();
			 					   if(Integer.parseInt(lateTmie1)>=(diff/60000)){
			 						   attendanceStatu = "1";
			 					   }else if(Integer.parseInt(lateTmie2)<(diff/60000) &&Integer.parseInt(lateTmie3)>(diff/60000)){
			 						  if(attendanceStatu1.equals("5")){
			 							 lateTime = "0";
				 						 amount = "0"; 
			 						  }else{
			 							 DecimalFormat    def   = new DecimalFormat("######0.00");   
			 							 lateTime = def.format((diff/60000.0))+"";
				 						 amount = def.format((diff/60000.0/timeBase)*debitType)+"";
				 						lateTime = lateTime.substring(0, lateTime.indexOf("."));
										 amount = amount.substring(0, amount.indexOf("."));
			 						  }
			 						 attendanceStatu = "3";
			 					   }else{
			 						  lateTime = AttendanceMethods.TimeDifference(signTime1,signoutTime);
			 							 if(num.equals("4")){
				 							 lateTime = AttendanceMethods.TimeDifference(signTime2,signoutTime2);
				 						  }
							    	   attendanceStatu = "5";
			 					   }
			 				}
					}
					catch (Exception e)
					{
					}
				}else{
					attendanceStatu = "4";
				}
			 
			 if(!attendanceStatu1.equals("1") && !attendanceStatu1.equals("4") ){
					try
					{
			  		    Date sg = df2.parse(signTimes);
			  		    Date ct = df2.parse(clockTime1);
			  		  if((sg.getTime() - ct.getTime())>=0 ){
			  			attendanceStatu1 = "1";
		 				}else{
		 					   long diff = ct.getTime() - sg.getTime();
		 					   if(Integer.parseInt(lateTmie1)>=(diff/60000)){
		 						  attendanceStatu1 = "1";
		 					   }else if(Integer.parseInt(lateTmie2)<(diff/60000) &&Integer.parseInt(lateTmie3)>(diff/60000)){
		 						  if(attendanceStatu.equals("5")){
		 							 lateTime1 = "0";
			 						   amount1 = "0";
		 						  }else{
		 							 DecimalFormat    def   = new DecimalFormat("######0.00");   
		 							   lateTime1 = def.format((diff/60000.0))+"";
			 						   amount1 = def.format((diff/60000.0/timeBase)*debitType)+"";
			 						  lateTime1 = lateTime1.substring(0, lateTime1.indexOf("."));
									   amount1 = amount1.substring(0, amount1.indexOf("."));
		 						  }
		 						 attendanceStatu1 = "2";
		 					   }else{
		 						  if(attendanceStatu.equals("5")){
		 							 lateTime1 ="0";
		 						  }else{
		 							 lateTime1 = AttendanceMethods.TimeDifference(signTime1,signoutTime);
		 							 if(num.equals("4")){
			 							 lateTime1 = AttendanceMethods.TimeDifference(signTime2,signoutTime2);
			 						  }
		 						  }
								   attendanceStatu1 = "5";
		 					   }
		 				}
					}
					catch (Exception e)
					{
					}
				}
			 p1.put("attendanceStatu", attendanceStatu1);
			 p1.put("amount", amount1);
			 p1.put("lateTime", lateTime1);
			 p1.put("clockTime", clockTime1);
			 int n = attenRecordDao.attenRecordDataUpdate(p1);
		  }
			  
		HashMap<String, String> param1 = new HashMap<String, String>();
		param1.put("recId", params.get("recId"));
		param1.put("num", params.get("num"));
		param1.put("attendanceStatu", attendanceStatu);
		param1.put("amount", amount);
		param1.put("lateTime", lateTime);
		param1.put("clockTime", clockTime);
		String msg = "";
		 int n = attenRecordDao.attenRecordDataUpdate(param1);
			if (n == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
			}
		HashMap<String, String> param = new HashMap<String, String>();
		param.put("recId", params.get("recId"));
		String st = "0";
		List list = attenRecordDao.getAttenRecordData(param);
		for (int i = 0; i < list.size(); i++) {
			param = (HashMap<String, String>) list.get(i);
			if(!param.get("ATTENDANCE_STATU").equals("1")){
				st = "1";
			}
		}
		HashMap<String, String> param2 = new HashMap<String, String>();
		param2.put("recId", params.get("recId"));
		param2.put("dataSta", "1");
		param2.put("attendanceStatu", st);
		attenRecordUpdate(param2);
		return msg;
	}

	@Override
	public String attenRecordUpdate(HashMap<String, String> params) {
		String msg = "";
		int n = attenRecordDao.attenRecordUpdate(params);
			if (n == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
			}
		return msg;
	}
	
	@Override
	public Map getAttenRecordData(HashMap<String, String> params) {
		List list = attenRecordDao.getAttenRecordData(params);
		if (list != null && list.size() > 0) {
			return (Map) list.get(0);
		}
		
		return null;
	}
	@Override
	public void exportAttendance(HashMap<String, String> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
		List dataList = attenRecordDao.exportAttendance(params);
		String recId = UUID.randomUUID().toString();
		String realPath = request.getSession().getServletContext().getRealPath("/file/temp");
		EXCELObject s = new EXCELObject();
		s.seteFilePath(realPath);
		String[] titH = { "日期", "姓名", "工号", "所属班组","所属排班","首次签到","首次签退","二次签到","二次签退", "工时","考勤状态","数据状态" };
		String[] titN = { "ATTENCE_TIME","NAME","JOBNO","GROUPNAME","ORG_NAME","SIGN_TIME","SIGNOUT_TIME","SIGN_TIME2","SIGNOUT_TIME2","WORKING_HOURS","ATTENDANCE_STATUSN","DATE_STATUS" };
		s.setFname("考勤数据 "); // 临时文件名
		s.setTitle("考勤数据"); // 大标题名称
		s.setTitH(titH);
		s.setTitN(titN);
		s.setDataList(dataList);
		File exportFile = null;
		exportFile = s.setData();
		String excelName = "考勤数据" + DateUtil.getCurrentTime() + ".xls";
		s.exportExcel("考勤数据", excelName, exportFile, request, response);

	}

	
	@Override
	public int getAttenRecordsCots(HashMap<String, String> params) {
		return attenRecordDao.getAttenRecordsCots(params);
	}

	@Override
	public List<?> findAttenRecords(HashMap<String, String> params) {
		return attenRecordDao.findAttenRecords(params);
	}
}
